import { useUserStore } from '@/stores'
import router from '@/router'
// axios配置
import axios from 'axios'
import { showToast } from 'vant'

const baseURL = 'https://consult-api.itheima.net/'

const instance = axios.create({
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    const store = useUserStore()
    if (store.userInfo?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.userInfo.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code !== 10000) {
      showToast(res.data.message || '网络异常')
      Promise.reject(res.data)
    }
    return res.data
  },
  (err) => {
    // 处理登录失效
    if (err.response.status === 401) {
      const store = useUserStore()
      store.delUser()
      showToast('登录超时请重新登录！')
      router.push({
        path: '/login',
        query: {
          // 方便重新登录后回到重新登录之前的页面
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }

    return Promise.reject(err)
  }
)

export { baseURL, instance }
